<template>
  <div class="page-wrap">
    <div class="top-wrap">
      车间 <Gap />
      <el-select :popper-append-to-body="false" v-model="currentWorkshop" placeholder="请选择车间">
        <el-option v-for="item in workshops" :key="item.id" :label="item.wname" :value="item.id" />
      </el-select>
      <Gap /> 机台 <Gap />
      <el-select :popper-append-to-body="false" v-model="currentMid" placeholder="请选择机台" style="width: 220px">
        <el-option v-for="item in macLis" :key="item.id" :label="item.mname + '(' + item.mid + ')'" :value="item.mid" />
      </el-select>
      <Gap />
      <el-radio-group v-model="currentSideZh"> <el-radio-button label="左边" /> <el-radio-button label="右边" /> </el-radio-group>
      <div style="flex: 1"></div>
      <div class="top-tips">参考速度：{{ currentMacBaseInfo.RefSpeed || '-' }}</div>
      <div class="top-tips" style="margin: 0 30px 0 20px">转速：{{ currentMacBaseInfo.LF_Roller_SP || '-' }}</div>
    </div>
    <div class="top-wrap" style="margin-top: 20px">
      <template v-for="(st, inx) in stateZh">
        <el-badge :value="stateCount[inx]" class="item" type="primary" :key="st">
          <div class="badge-content" :style="stateStyle[inx]">{{ st }}</div>
        </el-badge>
        <GapX :key="'gap' + inx"></GapX>
      </template>
    </div>
    <div class="spin-status">
      <div class="spin-list-row sort-top-tips">
        <div class="spin-list-col" style="border-right: 1px solid #ddd">
          <div class="spin-list-title">{{ currentSideZh }}</div>
        </div>
        <div class="spin-list-col" style="border-right: 1px solid #ddd" v-for="col in 24" :key="'inx' + col">
          <div class="spin-list-title">{{ col | twoNum }}</div>
        </div>
      </div>
      <div style="display: flex; flex-wrap: wrap; box-sizing: border-box">
        <template v-if="spindleList[currentMid]">
          <template v-for="inx in spindleCount">
            <div v-if="(inx - 1) % 24 == 0" class="spin-list-col" :key="inx">
              <div class="spin-list-item" style="height: 50%; align-items: center; justify-content: flex-end">{{ inx }}</div>
              <div class="spin-list-item" style="height: 50%; align-items: center; color: #bbb; justify-content: flex-start">
                ({{ (inx - 1) / 24 }})
              </div>
            </div>
            <div class="spin-list-col" :key="'x' + inx">
              <el-tooltip
                :content="
                  inx +
                  (currentSide === 'Right' ? 600 : 0) +
                  '-' +
                  stateZh[SPIN.State[inx - 1]] +
                  '-' +
                  (SPIN.Voltage[inx - 1] * 0.1).toFixed(1) +
                  'v'
                "
                placement="top"
                effect="light"
                :open-delay="300"
              >
                <div class="spin-list-item">
                  <span>{{ SPIN.Speed[inx - 1] }}</span>
                </div>
              </el-tooltip>
            </div>
          </template>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import cloneDeep from 'lodash/cloneDeep'

var showlog = true

export default {
  name: 'Spindle',
  components: {
    Gap: {
      template: `<div style="width:10px"></div>`,
    },
    GapX: {
      template: `<div style="width:20px"></div>`,
    },
  },
  filters: {
    twoNum(e) {
      return (e < 10 ? '0' : '') + e
    },
    thrNum(e) {
      return ('000' + e).slice(-3)
    },
  },
  data() {
    return {
      stateZh: ['正常', '超速', '弱捻', '断头', '空闲', '掉线'],
      stateColor: ['#FFF', '#FFF', '#FFF', '#FFF', '#444', '#555'],
      stateBgColor: ['#4CAF50', '#E6A23C', '#F56C6C', '#FF5722', '#CCC', '#DDD'],

      workshops: [],
      currentWorkshop: '',

      macLis: [],
      currentMid: '',
      currentMacBaseInfo: {},

      sideMap: { 左边: 'Left', 右边: 'Right' },
      currentSideZh: '左边',

      spindleList: {},
    }
  },
  computed: {
    currentSide() {
      return this.sideMap[this.currentSideZh]
    },
    spindleCount() {
      return this.currentSideZh == '左边' ? this.currentMac.leftSideTotal : this.currentMac.rightSideTotal
    },
    SPIN() {
      // console.log(' spindleList[currentMac][this.currentSide]', this.spindleList, this.currentMid)
      if (this.spindleList[this.currentMid]) {
        return this.spindleList[this.currentMid][this.currentSide]
      } else {
        return {}
      }
    },

    stateCount() {
      if (this.SPIN.State) {
        return this.SPIN.State.reduce(
          (pre, cur) => {
            pre[cur]++
            return pre
          },
          [0, 0, 0, 0, 0, 0]
        )
      } else {
        return [0, 0, 0, 0, 0, 0]
      }
    },

    stateStyle() {
      const _style = []
      for (let inx in this.stateColor) {
        _style.push({ background: this.stateBgColor[inx], color: this.stateColor[inx] })
      }
      return _style
    },
  },
  watch: {},
  created() {},
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      try {
        this.$ShowLoading()
        let r = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql: `select * from workshop_info order by wid`, pagenum: 1, pagesize: 100 },
        })
        this.workshops = r.obj.list
        this.currentWorkshop = this.workshops[0].id

        r = await request({
          url: '/db/getData',
          method: 'post',
          data: { sql: `select * from mac_info where workShop = '${this.currentWorkshop}' order by mid`, pagenum: 1, pagesize: 100 },
        })
        this.macLis = r.obj.list
        this.currentMid = this.macLis[0].mid

        await this.initSpindleList()
        this.$EVBUS.$on('Spindle', (data) => {
          // showlog && console.log(`Spindle eventbus on:`, data)
          if (data.id != this.currentMid) return

          const {
            id,
            Param: { Side, StartAddr, Number, Speed, State, Voltage },
          } = data

          const t = cloneDeep(this.spindleList)
          const dataOfSide = t[id][Side]

          for (let x = 0; x < Number; x++) {
            dataOfSide['Speed'][StartAddr + x] = Speed[x]
            dataOfSide['State'][StartAddr + x] = State[x]
            dataOfSide['Voltage'][StartAddr + x] = Voltage[x]
          }
          this.spindleList = t
        })

        this.$EVBUS.$on('MachineStatus', (data) => {
          if (data.id != this.currentMid) return
          // console.log('MachineStatus', data)
          this.currentMacBaseInfo = data.Param
        })
      } catch (e) {
        console.log(e)
      } finally {
        this.$CloseLoading()
      }
    },

    async initSpindleList() {
      this.currentMac = this.macLis.find((e) => e.mid == this.currentMid)
      const { mid, leftSideTotal, rightSideTotal } = this.currentMac
      if (!this.spindleList[mid]) {
        this.spindleList[mid] = {
          Left: { Speed: new Array(leftSideTotal).fill(1500), State: new Array(leftSideTotal).fill(1), Voltage: new Array(leftSideTotal).fill(0) },
          Right: {
            Speed: new Array(rightSideTotal).fill(1000),
            State: new Array(rightSideTotal).fill(2),
            Voltage: new Array(rightSideTotal).fill(5),
          },
        }
      }
      // console.log('curMac', this.spindleList)
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~@/styles/variables.scss';
.page-wrap {
  padding: 10px 20px;
  box-sizing: border-box;
}

.top-wrap {
  display: flex;
  align-items: center;
}
.spin-status {
  margin-top: 10px;
  height: calc(100vh - 200px);
  min-width: 800px;
  overflow: auto;
  border: 1px solid #ddd;
}
.spin-list-row {
  // border-left: 1px solid #eee;
  // border-right: 1px solid #eee;
  display: flex;
  border-bottom: 1px solid #ddd;
}
.spin-list-col {
  width: 4%;
  height: 40px;
  //padding: 4px;
  box-sizing: border-box;

  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

.spin-list-item {
  position: relative;
  color: #333;
  width: 100%;
  height: 100%;
  //box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  //border-radius: 4px;
  display: flex;
  font-size: 12px;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.spin-list-title {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  letter-spacing: 1px;
}
::v-deep .el-select .el-select-dropdown .el-scrollbar {
  padding-bottom: 15px !important;
}

.badge-content {
  padding: 5px 15px;
  font-size: 12px;
  border-radius: 3px;
  // border: 1px solid #bbb;
  display: inline-block;
  overflow: visible;
  color: #666;
}
.sort-tips {
  position: absolute;
  top: 4px;
  left: 4px;
  z-index: -1;
  color: #ccc;
}
.sort-top-tips {
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  left: 0;
  background: #fff;
  z-index: 99;
}
.top-tips {
  color: #666;
  font-size: 14px;
}
</style>
